<template>
  <div class="settings-container">
    <el-form
        v-if="!loading"
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-position="top"
        @submit.prevent="handleSave"
    >
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-title">
            <el-icon><Cpu /></el-icon>
            <span>车辆控制设置</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="车辆IP地址" prop="host">
              <el-input v-model="formModel.host" placeholder="请输入车辆IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="硬件驱动端口" prop="drivePort">
              <el-input-number v-model="formModel.drivePort" :min="1" :max="65535" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分析程序端口" prop="analysisPort">
              <el-input-number v-model="formModel.analysisPort" :min="1" :max="65535" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-title">
            <el-icon><Cloudy /></el-icon>
            <span>云端平台设置</span>
          </div>
        </template>
        <el-form-item label="云端平台地址" prop="cloudUrl">
          <el-input v-model="formModel.cloudUrl" placeholder="请输入云端平台地址" />
        </el-form-item>
      </el-card>

      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-title">
            <el-icon><CameraFilled /></el-icon>
            <span>摄像头设置</span>
          </div>
        </template>
        <div v-for="i in 4" :key="i" class="camera-group">
          <div class="camera-title">摄像头 {{ i }}</div>
          <el-form-item :label="`摄像头${i}地址`">
            <el-input v-model="formModel[`cam${i}`]" :placeholder="`请输入摄像头${i}地址`" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="`摄像头${i}登录名`">
                <el-input v-model="formModel[`username${i}`]" :placeholder="`请输入摄像头${i}登录名`" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="`摄像头${i}密码`">
                <el-input v-model="formModel[`password${i}`]" type="password" show-password :placeholder="`请输入摄像头${i}密码`" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <div class="btn-group">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" :loading="settingsStore.loading" @click="handleSave">
          保存设置
        </el-button>
      </div>
    </el-form>

    <div v-else v-loading="loading" class="loading-state"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useSettingsStore } from '@/stores/settings';
import { storeToRefs } from 'pinia';
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElCard,
  ElRow,
  ElCol,
  ElButton,
  ElIcon,
  ElMessage,
  vLoading,
} from 'element-plus';
import { Cpu, Cloudy, CameraFilled } from '@element-plus/icons-vue';

// 定义emits，用于通知父组件
const emit = defineEmits(['save-success', 'cancel']);

// --- Store and State ---
const settingsStore = useSettingsStore();
const { config, loading } = storeToRefs(settingsStore); // 从store中获取响应式状态

const formRef = ref(null); // 表单实例的引用
const formModel = ref({}); // 本地表单数据模型

// --- Validation Rules ---
const formRules = {
  host: [
    { required: true, message: '请输入车辆IP地址', trigger: 'blur' },
    {
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: '请输入有效的IP地址',
      trigger: 'blur',
    },
  ],
  drivePort: [{ required: true, message: '请输入硬件驱动端口', trigger: 'blur' }],
  analysisPort: [{ required: true, message: '请输入分析程序端口', trigger: 'blur' }],
  cloudUrl: [{ required: true, message: '请输入云端平台地址', trigger: 'blur' }],
};

// --- Watchers ---
// 监听store中config的变化，将其深拷贝到本地formModel
// 这样可以避免直接修改store中的状态，只有在保存时才提交
watch(
    config,
    (newConfig) => {
      formModel.value = JSON.parse(JSON.stringify(newConfig));
    },
    { deep: true, immediate: true }
);

// --- Methods ---
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    // 触发表单验证
    await formRef.value.validate();
    // 验证通过，调用store的action来保存配置
    await settingsStore.saveConfig(formModel.value);
    // 保存成功后，触发save-success事件，通知父组件
    emit('save-success');
  } catch (validationErrors) {
    ElMessage.error('表单校验失败，请检查输入项。');
    console.log('Validation Errors:', validationErrors);
  }
};

const handleCancel = () => {
  // 重置表单为store中的原始数据
  formModel.value = JSON.parse(JSON.stringify(config.value));
  // 触发cancel事件，通知父组件（例如关闭弹窗）
  emit('cancel');
};

// --- Lifecycle Hooks ---
onMounted(() => {
  // 组件挂载时，如果store中没有数据，则从后端获取一次
  if (!config.value.host) {
    settingsStore.fetchConfig();
  }
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.settings-container {
  padding: 10px;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: $font-size-medium;
  font-weight: bold;
  gap: 8px;
}

.camera-group {
  border: 1px solid $border-color-light;
  border-radius: $border-radius-base;
  padding: 15px;
  margin-bottom: 15px;
  background: #fafcff;

  &:last-child {
    margin-bottom: 0;
  }
}

.camera-title {
  font-size: $font-size-base;
  font-weight: bold;
  margin-bottom: 15px;
  color: $text-color-regular;
}

.btn-group {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid $border-color-light;
}

.loading-state {
  min-height: 400px;
}
</style>